package com.goldmantis.activemq.ch2.jobs;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class ConsumerTextMessage2 implements MessageListener{

    private static String brokerURL = "tcp://localhost:51616";
    private static transient ConnectionFactory factory;
    private transient Connection connection;
    private transient Session session;
    private static int retryCount = 0;
    
    private String jobs[] = new String[]{"suspend"};
    
    public ConsumerTextMessage2() throws JMSException {
    	factory = new ActiveMQConnectionFactory(brokerURL);
    	connection = factory.createConnection();
    	connection.setClientID("queueConsumer");
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    }
    
    public void close() throws JMSException {
        if (connection != null) {
            connection.close();
        }
    }    
    
    public static void main(String[] args) throws JMSException {
    	ConsumerTextMessage2 consumer = new ConsumerTextMessage2();
		Destination destination = consumer.getSession().createQueue("JOBS.suspend");
    	String filter = "sign = 'helloworld'";		
		MessageConsumer messageConsumer = consumer.getSession().createConsumer(destination,filter);
		//ObjectMessage msg = (ObjectMessage)messageConsumer.receive();
/*    		System.out.println(msg.getObject());
		while(msg != null){
			msg = (ObjectMessage)messageConsumer.receive();
    		System.out.println(msg.getObject());
		}*/
		messageConsumer.setMessageListener(consumer);
    }
    
	public void onMessage(Message message) {
		retryCount++;
		try {
			//do something here
			//System.out.println("消息属性sign:\r"+message.getStringProperty("sign"));
			//System.out.println(((TextMessage)message).getText());
			System.out.println("接收数据第几次:"+retryCount);
			System.out.println(((TextMessage)message).getJMSRedelivered());
		} catch (Exception e) {
			e.printStackTrace();
		}
		throw new RuntimeException("test");		
	}    
	
	public Session getSession() {
		return session;
	}


}
